<template>
  <div class="course-form-container">
    <el-card class="course-form-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑课程' : '添加课程' }}</h2>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="course-form"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称" />
        </el-form-item>

        <el-form-item label="授课教师" prop="teacher">
          <el-input v-model="form.teacher" placeholder="请输入授课教师姓名" />
        </el-form-item>

        <el-form-item label="实验数量" prop="experimentCount">
          <el-input-number v-model="form.experimentCount" :min="0" :max="20" />
        </el-form-item>

        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存修改' : '添加课程' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import logger from '@/utils/Logger'

export default {
  name: 'CourseForm',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const formRef = ref(null)

    // 状态
    const submitting = ref(false)
    const form = reactive({
      id: '',
      name: '',
      teacher: '',
      experimentCount: 0,
      classCount: 0,
      description: ''
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 2, max: 50, message: '课程名称长度应为2-50个字符', trigger: 'blur' }
      ],
      teacher: [
        { required: true, message: '请输入授课教师姓名', trigger: 'blur' }
      ],
      experimentCount: [
        { required: true, message: '请输入实验数量', trigger: 'blur' }
      ]
    }

    // 计算属性
    const isEdit = computed(() => {
      return route.params.id !== undefined
    })

    // 方法
    const loadCourseData = () => {
      if (isEdit.value) {
        const courseId = route.params.id
        const courseData = store.getters.getCourses.find(c => c.id === courseId)

        if (courseData) {
          Object.assign(form, courseData)
          logger.info('课程数据加载成功', { courseId })
        } else {
          ElMessage.error('未找到课程数据')
          router.push('/course/list')
        }
      }
    }

    const submitForm = async () => {
      if (!formRef.value) return

      await formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true

          try {
            // 确保 experimentCount 是数字类型
            if (form.experimentCount && typeof form.experimentCount === 'string') {
              form.experimentCount = parseInt(form.experimentCount, 10)
            }

            console.log('Form data before submission:', form)

            if (isEdit.value) {
              // 更新课程
              await store.dispatch('updateCourse', { id: form.id, courseData: form })
              ElMessage.success('课程更新成功')
              logger.info('课程更新成功', { courseId: form.id, courseName: form.name })
            } else {
              // 添加课程
              const newCourse = {
                name: form.name,
                teacher: form.teacher,
                experimentCount: form.experimentCount || 0
              }
              console.log('Creating new course:', newCourse)
              await store.dispatch('createCourse', newCourse)
              ElMessage.success('课程添加成功')
              logger.info('课程添加成功', { courseName: newCourse.name })
            }

            router.push('/course/list')
          } catch (error) {
            logger.error(isEdit.value ? '更新课程失败' : '添加课程失败', error)
            ElMessage.error(isEdit.value ? '更新课程失败' : '添加课程失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const goBack = () => {
      router.push('/course/list')
    }

    // 生命周期钩子
    onMounted(() => {
      loadCourseData()
    })

    return {
      formRef,
      form,
      rules,
      isEdit,
      submitting,
      submitForm,
      goBack
    }
  }
}
</script>

<style scoped>
.course-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.course-form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.course-form {
  margin-top: 20px;
}
</style>
